<?php

namespace App\Services;

class CommandHandler
{
    protected $commands = [];

    public function __construct()
    {
        $this->registerCommands();
    }

    public function handle($command, $arguments = [])
    {
        // 在 handle 方法内部进行彻底清理
        $cleanCommand = InputFilter::cleanInput($command);
        $cleanCommand = strtolower(trim($cleanCommand));
        
        // 清理参数
        $cleanArguments = [];
        foreach ($arguments as $arg) {
            $cleanArg = InputFilter::cleanInput($arg);
            if (!empty($cleanArg)) {
                $cleanArguments[] = $cleanArg;
            }
        }
        
        echo "处理命令: '{$cleanCommand}' 参数: " . json_encode($cleanArguments) . "\n";
        
        if (empty($cleanCommand)) {
            return "Empty command";
        }
        
        if (!isset($this->commands[$cleanCommand])) {
            return "Unknown command: {$cleanCommand}. Available: " . implode(', ', array_keys($this->commands));
        }

        return call_user_func($this->commands[$cleanCommand], $cleanArguments);
    }


    protected function registerCommands()
    {
        // 只注册核心命令
        $this->commands = [
            'mul' => function($args) {
                return count($args) === 2 ? $args[0] * $args[1] : "Usage: mul x y";
            },
            'incr' => function($args) {
                return count($args) === 1 ? $args[0] + 1 : "Usage: incr x";
            },
            'div' => function($args) {
                if (count($args) !== 2) return "Usage: div x y";
                return $args[1] == 0 ? "Error: Division by zero" : $args[0] / $args[1];
            },
              'conv_tree' => function($args) {
                $data = [
                    ["id" => 200002538, "name" => "空心菜类", "level" => 3, "namePath" => "蔬菜/豆制品,叶菜类,空心菜类"],
                    ["id" => 200002537, "name" => "香菜类", "level" => 3, "namePath" => "蔬菜/豆制品,葱姜蒜椒/调味菜,香菜类"],
                    ["id" => 200002536, "name" => "紫苏/苏子叶", "level" => 3, "namePath" => "蔬菜/豆制品,叶菜类,紫苏/苏子叶"],
                    ["id" => 200002543, "name" => "乌塌菜/塌菜/乌菜", "level" => 3, "namePath" => "蔬菜/豆制品,叶菜类,乌塌菜/塌菜/乌菜"],
                    ["id" => 200002542, "name" => "菜心/菜苔类", "level" => 3, "namePath" => "蔬菜/豆制品,叶菜类,菜心/菜苔类"],
                    ["id" => 200002540, "name" => "马兰头/马兰/红梗菜", "level" => 3, "namePath" => "蔬菜/豆制品,叶菜类,马兰头/马兰/红梗菜"],
                    ["id" => 200002531, "name" => "苋菜类", "level" => 3, "namePath" => "蔬菜/豆制品,叶菜类,苋菜类"],
                    ["id" => 200002528, "name" => "其他叶菜类", "level" => 3, "namePath" => "蔬菜/豆制品,叶菜类,其他叶菜类"]
                ];

           
                // 确保输出是 UTF-8 编码
                $output = $this->buildCategoryTree($data);

             
                return json_encode($output,JSON_UNESCAPED_UNICODE);
            },
            'help' => function($args) {
                return "Commands: mul, incr, div, conv_tree, help, exit";
            },
            'exit' => function($args) {
                return "Goodbye";
            }
        ];
    }


    function generateRandomId($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $result = '';
    for ($i = 0; $i < $length; $i++) {
        $result .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $result;
    }

    function buildCategoryTree($data) {
    // 创建根节点
    $rootId =$this->generateRandomId();
    $tree = [
        "id" => $rootId,
        "id_path" => ",{$rootId},",
        "is_leaf" => 2,
        "level" => 1,
        "name" => "蔬菜/豆制品",
        "name_path" => "蔬菜/豆制品",
        "parent_id" => 0,
        "children" => []
    ];
    
    // 用于存储二级分类的映射
    $secondLevelMap = [];
    
    foreach ($data as $item) {
        // 解析namePath获取各级分类名称
        $namePath = $item['namePath'];
        $pathParts = explode(',', $namePath);
        
        if (count($pathParts) < 3) {
            continue;
        }
        
        $secondLevelName = $pathParts[1]; // 二级分类名称
        $thirdLevelName = $pathParts[2];  // 三级分类名称
        
        // 如果二级分类还不存在，创建它
        if (!isset($secondLevelMap[$secondLevelName])) {
            $secondLevelId = $this->generateRandomId();
            $secondLevelMap[$secondLevelName] = [
                "id" => $secondLevelId,
                "id_path" => ",{$rootId},{$secondLevelId},",
                "is_leaf" => 2,
                "level" => 2,
                "name" => $secondLevelName,
                "name_path" => "{$pathParts[0]},{$secondLevelName}",
                "parent_id" => $rootId,
                "children" => []
            ];
            $tree['children'][] = &$secondLevelMap[$secondLevelName];
        }
        
        // 添加三级分类
        $thirdLevelNode = [
            "id" => (string)$item['id'],
            "id_path" => ",{$rootId},{$secondLevelMap[$secondLevelName]['id']}," . (string)$item['id'] . ",",
            "is_leaf" => 1,
            "level" => 3,
            "name" => $item['name'],
            "name_path" => $item['namePath'],
            "parent_id" => $secondLevelMap[$secondLevelName]['id']
        ];
        
        $secondLevelMap[$secondLevelName]['children'][] = $thirdLevelNode;
    }
    
    return $tree;
    }


}